﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;
using ResortModule;

namespace MBBHotelReservation
{
    public partial class frmMonitoringManager : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();
        string search = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
        
        DataTable items = new DataTable();
        DataTable items2 = new DataTable();

        public DataTable hotelRoom = new DataTable();
        public DataTable availedRoom = new DataTable();
        public DataTable functionHall = new DataTable();

        public string room = "";
        public float dayTimeFee = 0.0f;
        public float overNightFee = 0.0f;
        public float oneDayFee = 0.0f;
        public bool isMaintain = false;
        public bool isWhite = false;
        bool isViewByDate = false;
        //AutoChecker
        Timer tmr = new Timer();

        frmMain parent;

        public frmMonitoringManager(frmMain p)
        {
            parent = p;
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);

            //Start AutoCheck timer
            tmr.Interval = 500;
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Enabled = true;
            LoadData(search);

            //events
           // btnCheckIn.Click += new EventHandler(btnCheckIn_Click);
            btnRefresh.Click += new EventHandler(btnRefresh_Click);
            btnView.Click += new EventHandler(btnView_Click);
            btnAddHKRoom.Click += new EventHandler(btnAddMaintenance_Click);
            btnHKHall.Click += new EventHandler(btnAddMaintenanceHall_Click);
            btnMHall.Click += new EventHandler(btnMHall_Click);
            btnMRoom.Click += new EventHandler(btnMRoom_Click);

            btnRoomInfo.Click += new EventHandler(btnRoomInfo_Click);
            btnHallInfo.Click += new EventHandler(btnHallInfo_Click);
        }

        void btnHallInfo_Click(object sender, EventArgs e)
        {
            if (grdItems2.SelectedCells.Count == 1)
            {
                string colorOfRoom = grdItems2.SelectedCells[0].Style.BackColor.Name.ToString();
                string roomNumber = ""; 
                roomNumber = grdItems2.SelectedCells[0].Value.ToString();
                UnityScript us = new UnityScript("GETTRANSNUM", 5);
                us.Script_Add(Script.DBPUX_BEGIN);
                if (colorOfRoom.Equals("Green"))
                {
                    us.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fTransNum, fStamp FROM tblMonitoring WHERE fRoom = '" + roomNumber + "' AND fTransactionMode = 'Occupied'"));
                }
                else if (colorOfRoom.Equals("Blue"))
                {
                    //Debug history - Wrong keyword used Reserved instead of Reserve.
                    //us.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fTransNum, fStamp FROM tblMonitoring WHERE fRoom = '" + roomNumber + "' AND fTransactionMode = 'Reserved'"));

                    us.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fTransNum, fStamp FROM tblMonitoring WHERE fRoom = '" + roomNumber + "' AND fTransactionMode = 'Reserve'"));

                }
                us.Script_Add(Script.DBPUX_COMMIT);
                proc.Run(us);
            }
        }

        void btnRoomInfo_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedCells.Count == 1)
            {
                string colorOfRoom = grdItems.SelectedCells[0].Style.BackColor.Name.ToString();
                string roomNumber ="";
                roomNumber = grdItems.SelectedCells[0].Value.ToString();
                UnityScript u = new UnityScript("GETTRANSNUM", 5);
                u.Script_Add(Script.DBPUX_BEGIN);
                if ( colorOfRoom.Equals("Green"))
                {
                    u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fTransNum, fStamp FROM tblMonitoring WHERE fRoom = '"+roomNumber+"' AND fTransactionMode = 'Occupied'"));
                }
                else if (colorOfRoom.Equals("Blue"))
                {
                    u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fTransNum, fStamp FROM tblMonitoring WHERE fRoom = '" + roomNumber + "' AND fTransactionMode = 'Reserve'"));
                    
                }
                u.Script_Add(Script.DBPUX_COMMIT);
                proc.Run(u);
            }
        }

        void btnMRoom_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedCells.Count == 1)
            {
                isMaintain = true;
                room = "";
                room = grdItems.SelectedCells[0].Value.ToString();
                //string timeOfViewing = txtSearchDate.Text;
                string colorOfRoom = grdItems.SelectedCells[0].Style.BackColor.Name.ToString();
                if (colorOfRoom.Equals("White"))
                {
                    isWhite = true;
                    frmMaintenance frm = new frmMaintenance(this);
                    frm.ShowDialog();
                }
                else if (colorOfRoom.Equals("Red"))
                {
                    isWhite = false;
                    frmMaintenance frm = new frmMaintenance(this);
                    frm.ShowDialog();
                }

            }
        }

        void btnMHall_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedCells.Count == 1)
            {
                isMaintain = true;
                room = "";
                room = grdItems2.SelectedCells[0].Value.ToString();
                //string timeOfViewing = txtSearchDate.Text;
                string colorOfRoom = grdItems2.SelectedCells[0].Style.BackColor.Name.ToString();
                if (colorOfRoom.Equals("White"))
                {
                    isWhite = true;
                    frmMaintenance frm = new frmMaintenance(this);
                    frm.ShowDialog();
                }
                else if (colorOfRoom.Equals("Red"))
                {
                    isWhite = false;
                    frmMaintenance frm = new frmMaintenance(this);
                    frm.ShowDialog();
                }
            }
        }

        void btnAddMaintenanceHall_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedCells.Count == 1)
            {
                room = "";
                isMaintain = false;
                room = grdItems2.SelectedCells[0].Value.ToString();
                //string timeOfViewing = txtSearchDate.Text;
                string colorOfRoom = grdItems2.SelectedCells[0].Style.BackColor.Name.ToString();
                if (colorOfRoom.Equals("Orange") )
                {
                    frmMaintenance frm = new frmMaintenance(this);
                    frm.ShowDialog();
                }

               
            }
            
        }

        void btnAddMaintenance_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedCells.Count == 1)
            {
                isMaintain = false;
                room = "";
                room = grdItems.SelectedCells[0].Value.ToString();
                //string timeOfViewing = txtSearchDate.Text;
                string colorOfRoom = grdItems.SelectedCells[0].Style.BackColor.Name.ToString();
                if (colorOfRoom.Equals("Orange") )
                {
                    frmMaintenance frm = new frmMaintenance(this);
                    frm.ShowDialog();
                }
                
            }
            
        }
        void btnView_Click(object sender, EventArgs e)
        {
            DateTime dateSearch = DateTime.Parse(txtSearchDate.Text);
            search = dateSearch.ToString("yyyy-MM-dd HH:mm:00");
            LoadData(search);    
        }
        void btnRefresh_Click(object sender, EventArgs e)
        {
            txtSearchDate.Text = "";
            LoadData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:00"));
        }
        void btnCheckIn_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedCells.Count == 1)
            {
                room = "";
                dayTimeFee = 0.0f;
                overNightFee = 0.0f;
                oneDayFee = 0.0f;

                room = grdItems.SelectedCells[0].Value.ToString();

                if (!hotelRoom.Equals("") && (grdItems.SelectedCells[0].Style.BackColor == Color.White))
                {
                    t.MethodCall(lookForRate);
                }
                else if (!hotelRoom.Equals("") && (grdItems.SelectedCells[0].Style.BackColor == Color.Blue))
                {

                }
                else
                    MessageBox.Show("Please select available room... Thank you");
            }
            else
                MessageBox.Show("Please select Room from the grid... Thank you");
        }

        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "GETTRANSNUM":
                        UnityScript [] trans;
                        proc.DBPUX_Data_Fetch(out trans);
                        if (trans[0].Data_Count == 1)
                        {
                            UnityElement edat;
                            trans[0].Data_Get(0, out edat);
                            string transnum = edat.Data_GetField(0).ToString();
                            parent.loadTransactionManager(transnum, true);
                        }
                        break;
                    case "INITGEN":
                        LoadData(search);
                        break;
                    case "COMMIT":
                        btnClose_Click(null, null);
                        break;
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        hotelRoom = dat[0].ToDataTable();
                        availedRoom = dat[1].ToDataTable();
                        functionHall = dat[2].ToDataTable();

                        t.MethodCall(displayRooms);
                        break;
                };
                tmr.Enabled = true;
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch (sender.ToString())
                {
                    case "lookForRate": 
                        frmRoomReservation frm = new frmRoomReservation(this);
                        frm.ShowDialog();
                        break;    
                    case "displayRooms":
                        //hotel room
                        grdItems.DataSource = items;
                        grdItems.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
                        grdItems.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
                        grdItems.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
                        grdItems.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable;

                        //function hall
                        grdItems2.DataSource = items2;
                        grdItems2.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;

                        resetColor();

                        DateTime queryDate = DateTime.Parse(search);

                        for (int i = 0; i < availedRoom.Rows.Count; i++)
                        {
                            DateTime cIT = DateTime.Parse(availedRoom.Rows[i]["fCheckInDateTime"].ToString());
                        //    DateTime cOT = DateTime.Parse(availedRoom.Rows[i]["fCheckOutDateTime"].ToString());

                            if (queryDate.CompareTo(cIT) > 0)// && queryDate.CompareTo(cOT) < 0)
                            {
                                colorMonitoring(availedRoom.Rows[i]["fRoom"].ToString(), availedRoom.Rows[i]["fTransactionMode"].ToString());                   
                            }
                            if(queryDate.CompareTo(cIT) == 0) //|| queryDate.CompareTo(cOT)==0)
                                colorMonitoring(availedRoom.Rows[i]["fRoom"].ToString(), availedRoom.Rows[i]["fTransactionMode"].ToString());                   
                        }


                        
                        break;
                }
                tmr.Enabled = true;
            });
        }

        //Operations
        public void LoadData(string filter)
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            proc.ProcStart();
            UnityScript x = new UnityScript("LOAD", 5);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblRoomLookUp"));
            x.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblmonitoring WHERE (fCheckInDateTime <= '" + filter + "' AND fCheckOutDateTime >= '" + filter + "') OR " +
                "(fTransactionMode = 'Occupied' OR fTransactionMode = 'Reserve' OR fTransactionMode = 'Maintenance' OR fTransactionMode = 'HouseKeeping' OR fTransactionMode = 'Cleared')");
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblFunctionLookUp"));
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }
        
        void tmr_Tick(object sender, EventArgs e)
        {
            tmr.Enabled = false;
            //Calls that involves UnityProcessor.
            if (!proc.IsRunning)
            {
                t.MethodCall(delegate
                {
                    while (proc.IsRunning)
                    {
                        System.Threading.Thread.Sleep(1);
                    }
                    UnityScript u = new UnityScript("GENERATE", 4);
                    u.Script_Add(Script.DBPUX_BEGIN);
                    //generate auto room monitoring

                    //u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblpurchaseordergenerate"); ;
                    u.Script_Add(Script.DBPUX_COMMIT);
                    proc.Run(u);
                });
            }
        }
        void States(bool s)
        {
            grdItems.Enabled = s;
        }
        void displayRooms()
        {
            //hotel room
            items = new DataTable();
            items.Columns.Add("KS Building");
            items.Columns.Add("Barasoain Building");
            items.Columns.Add("Maharlika Building");
            items.Columns.Add("Centennial Building");

            items.Rows.Add(items.NewRow());
            int rw = 0;
            for (int j = 0; j < items.Columns.Count; j++)
            {
                rw = 0;
                for (int i = 0; i < hotelRoom.Rows.Count; i++)
                {
                    string data_field = hotelRoom.Rows[i]["fBuildingName"].ToString();
                    if (data_field.Equals(items.Columns[j].ColumnName))
                    {
                        if (j == 0)
                        {
                            if ((items.Rows[rw][j].ToString() != ""))
                            {
                                items.Rows.Add(items.NewRow());
                                rw++;
                                items.Rows[rw][j] = hotelRoom.Rows[i]["fRoomNumber"].ToString();
                            }
                            else
                            {
                                items.Rows[rw][j] = hotelRoom.Rows[i]["fRoomNumber"].ToString();
                            }
                        }
                        else
                        {
                            if (items.Rows.Count > rw)
                            {
                                items.Rows[rw][j] = hotelRoom.Rows[i]["fRoomNumber"].ToString();
                                rw++;
                            }
                            else
                            {
                                items.Rows.Add(items.NewRow());
                                items.Rows[rw][j] = hotelRoom.Rows[i]["fRoomNumber"].ToString();
                                rw++;
                            }
                        }
                    }
                }
            }

            //function hall
            items2 = new DataTable();
            items2.Columns.Add("Function Hall");

            for (int i = 0; i < functionHall.Rows.Count; i++)
            {
                items2.Rows.Add(functionHall.Rows[i][0].ToString());
            }
        }
        void resetColor()
        {
            //hotel room
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                for (int j = 0; j < grdItems.Columns.Count; j++)
                {
                    grdItems.Rows[i].Cells[j].Style.BackColor = Color.White;
                }
            }
            //function hall
            for (int i = 0; i < grdItems2.Rows.Count; i++)
            {
                for (int j = 0; j < grdItems2.Columns.Count; j++)
                {
                    grdItems2.Rows[i].Cells[j].Style.BackColor = Color.White;
                }
            }
        }
        void colorMonitoring(string rmNumber, string transactionMode)
        {
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                for (int j = 0; j < grdItems.Columns.Count; j++)
                {
                    if (grdItems.Rows[i].Cells[j].Value.ToString().Equals(rmNumber))
                    {
                        switch (transactionMode)
                        {
                            case "Maintenance": grdItems.Rows[i].Cells[j].Style.BackColor = Color.Red;
                                break;
                            case "HouseKeeping": grdItems.Rows[i].Cells[j].Style.BackColor = Color.Orange;
                                break;
                            case "Occupied": grdItems.Rows[i].Cells[j].Style.BackColor = Color.Green;
                                break;
                            case "Reserve": grdItems.Rows[i].Cells[j].Style.BackColor = Color.Blue;
                                break;
                            //Debug Note: Forced re-color to solve Reserve flag not clearing properly.
                            //XCoder
                            case "Cleared": grdItems.Rows[i].Cells[j].Style.BackColor = Color.White;
                                break;
                        }
                    }
                }
            }

            for (int i = 0; i < grdItems2.Rows.Count; i++)
            {
                for (int j = 0; j < grdItems2.Columns.Count; j++)
                {
                    if (grdItems2.Rows[i].Cells[j].Value.ToString().Equals(rmNumber))
                    {
                        switch (transactionMode)
                        {
                            case "Maintenance": grdItems2.Rows[i].Cells[j].Style.BackColor = Color.Red;
                                break;
                            case "HouseKeeping": grdItems2.Rows[i].Cells[j].Style.BackColor = Color.Orange;
                                break;
                            case "Occupied": grdItems2.Rows[i].Cells[j].Style.BackColor = Color.Green;
                                break;
                            case "Reserve": grdItems2.Rows[i].Cells[j].Style.BackColor = Color.Blue;
                                break;
                            //Debug Note: Forced re-color to solve Reserve flag not clearing properly.
                            //XCoder
                            case "Cleared": grdItems2.Rows[i].Cells[j].Style.BackColor = Color.White;
                                break;
                        }
                    }
                }
            }
        }
        void lookForRate()
        {
            for (int i = 0; i < hotelRoom.Rows.Count; i++)
            {
                string rmNumber = hotelRoom.Rows[i]["fRoomNumber"].ToString();
                if (room.Equals(rmNumber))
                {
                    dayTimeFee = float.Parse(hotelRoom.Rows[i]["fDayRate"].ToString());
                    overNightFee = float.Parse(hotelRoom.Rows[i]["fNightRate"].ToString());
                    oneDayFee = float.Parse(hotelRoom.Rows[i]["f24HoursRate"].ToString());
                    break;
                }
            }
        }
        //Printing Module
    
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}